package org.thirdHero.core.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;


public class MapUtil {
    //1、object转换成map
    public static Map<String, Object> Obj2Map(Object obj) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    //2、map转换为object
    public static <T> T map2Obj(Map<String, Object> map, Class<T> clz) throws Exception {
        T t = clz.newInstance();
        Field[] declaredFields = clz.getDeclaredFields();
        for (Field field : declaredFields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            String className = field.getType().getSimpleName();
            // 得到属性值
            if (className.equalsIgnoreCase("String"))
                field.set(t, map.get(field.getName()));
             else if (className.equalsIgnoreCase("int")) {
                field.set(t,  Integer.parseInt(map.get(field.getName()).toString()) );
            }else if(className.equalsIgnoreCase("long")){
                field.set(t,  Long.parseLong(map.get(field.getName()).toString()) );
            }else if(className.equalsIgnoreCase("date")){
                 field.set(t, DateHelper.dateToStamp(map.get(field.getName()).toString()));
            }
            field.set(t, map.get(field.getName()));
        }
        return t;
    }
}
